package conf

import (
	"encoding/json"
	"errors"
	"io/ioutil"
	"log"
	"os"
)

type options struct {
	Charset string
	ParseTime bool
}

type params struct {
	User string `json:"user"`
	Password string `json:"password"`
	Host string `json:"host"`
	Port string `json:"port"`
	Schema string `json:"schema"`
}

type Config struct {
	Ps params
	Opts options
}

type Option func(*options)

func New(opts ...Option) Config{
	o := options{
		Charset: "utf8",
		ParseTime: false,
	}

	//修改可选项的默认值
	for _, opt := range opts {
		opt(&o)
	}

	p := load()
	return Config{Ps :p, Opts: o}
}

func load() params {
	f, err := os.Open("config.json")
	if err != nil {
		log.Fatal(errors.New("load config errors"))
	}
	pa := &params{}
	configSrc, err := ioutil.ReadAll(f)
	if err != nil {
		log.Fatal(errors.New("load config errors"))
	}
	err = json.Unmarshal(configSrc, pa)
	if err != nil {
		log.Fatal(errors.New("load config errors"))
	}

	return *pa
}

func WithCharset(charset string) Option{
	return func(op *options) {
		op.Charset = charset
	}
}

func WithParseTime(parseTime bool) Option{
	return func(op *options) {
		op.ParseTime = parseTime
	}
}
